import { defineStore } from "pinia";
import { ref, watch } from "vue";

function initState() {
    return {
        isCollapse: false,
        tags: [
            {
                path: '/home',
                name: 'home',
                label: '首页',
                icon: 'home',
            }
        ],
        currentMenu: null,
        menuList: [],
        token: "",
        routerList: [],
    };
}

export const useAllDataStore = defineStore('allData', () => {
    const state = ref(initState());

    // 监听状态变化，保存到localStorage
    watch(
        state,
        (newObj) => {
            if (!newObj.token) return;
            try {
                localStorage.setItem("store", JSON.stringify(newObj));
            } catch (error) {
                console.error('保存状态到localStorage失败:', error);
            }
        },
        { deep: true }
    );

    // 选择菜单
    function selectMenu(val) {
        if (val.name === 'home') {
            state.value.currentMenu = null;
        } else {
            const index = state.value.tags.findIndex(item => item.name === val.name);
            if (index === -1) {
                state.value.tags.push(val);
            }
        }
    }

    // 更新标签
    function updateTags(tag) {
        const index = state.value.tags.findIndex((item) => item.name === tag.name);
        if (index !== -1) {
            state.value.tags.splice(index, 1);
        }
    }

    // 更新菜单列表
    function updateMenuList(val) {
        state.value.menuList = val;
    }

    // 添加菜单路由
    function addMenu(router, type) {
        try {
            if (type === 'refresh') {
                const storedState = localStorage.getItem('store');
                if (storedState) {
                    state.value = JSON.parse(storedState);
                    state.value.routerList = [];
                } else {
                    return;
                }
            }

            const menu = state.value.menuList;
            const module = import.meta.glob('../views/**/*.vue');
            const routeArr = [];

            menu.forEach(item => {
                if (item.children) {
                    item.children.forEach(val => {
                        const url = `../views/${val.url}.vue`;
                        if (module[url]) {
                            val.component = module[url];
                            routeArr.push(val);
                        } else {
                            console.warn(`找不到组件: ${url}`);
                        }
                    });
                } else {
                    const url = `../views/${item.url}.vue`;
                    if (module[url]) {
                        item.component = module[url];
                        routeArr.push(item);
                    } else {
                        console.warn(`找不到组件: ${url}`);
                    }
                }
            });

            // 清除现有路由
            state.value.routerList = [];
            const routers = router.getRoutes();
            routers.forEach(item => {
                if (!['main', 'login', '404'].includes(item.name)) {
                    router.removeRoute(item.name);
                }
            });

            // 添加新路由
            routeArr.forEach(item => {
                if (item.name && item.component) {
                    const route = router.addRoute("main", item);
                    state.value.routerList.push(route);
                }
            });
        } catch (error) {
            console.error('添加菜单路由失败:', error);
        }
    }

    // 清理状态
    function clean() {
        try {
            // 移除所有动态路由
            state.value.routerList.forEach(removeRoute => {
                if (typeof removeRoute === 'function') {
                    removeRoute();
                }
            });

            // 重置状态
            state.value = initState();

            // 清除本地存储
            localStorage.removeItem('store');
        } catch (error) {
            console.error('清理状态失败:', error);
        }
    }

    return {
        state,
        selectMenu,
        updateTags,
        updateMenuList,
        addMenu,
        clean
    };
});